package com.cvmars.jianyou.module.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.api.model.QiNiuModel;
import com.cvmars.jianyou.api.model.UserMode;
import com.cvmars.jianyou.config.MyConfig;
import com.cvmars.jianyou.model.ImageModel;
import com.cvmars.jianyou.model.UserInfoManager;
import com.cvmars.jianyou.model.UserModel;
import com.cvmars.jianyou.module.base.BaseActivity;
import com.cvmars.jianyou.module.fragment.ChatFragment;
import com.cvmars.jianyou.module.fragment.ChatIMFragment;
import com.cvmars.jianyou.module.fragment.FindFragment;
import com.cvmars.jianyou.module.fragment.HomeFragment;
import com.cvmars.jianyou.module.fragment.IndexFragment;
import com.cvmars.jianyou.module.fragment.MeSettingFragment;
import com.cvmars.jianyou.module.fragment.MessageFragment;
import com.cvmars.jianyou.module.fragment.TaskFragment;
import com.cvmars.jianyou.module.listener.PermissionListener;
import com.cvmars.jianyou.module.model.AppConfigModel;
import com.cvmars.jianyou.module.model.EventAppExit;
import com.cvmars.jianyou.utils.DensityUtils;
import com.cvmars.jianyou.utils.DeviceHelper;
import com.cvmars.jianyou.utils.DownloadApkThread;
import com.cvmars.jianyou.utils.LogUtils;
import com.cvmars.jianyou.utils.ToastUtils;
import com.cvmars.jianyou.utils.UtilHelper;
import com.cvmars.jianyou.widget.ArrowDownloadButton;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

public class HomeActivity extends BaseActivity implements View.OnClickListener {

    FragmentManager fragmentManager;

    FragmentTransaction fragmentTransaction;

    MessageFragment messageFragment;

    MeSettingFragment settingFragment;

    HomeFragment indexFragment;

    ChatIMFragment imFragment;

    ChatFragment chatFragment;

    FindFragment findFragment;

    TextView txtTab1, txtTab2, txtTab3, txtTab4;
    ImageView ivTab1, ivTab2, ivTab3, ivTab4;


    private long mExitTime;
    public static final long TWO_SECOND = 2 * 1000;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;


    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {


            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
//可在其中解析amapLocation获取相应内容。

                    double latitude = amapLocation.getLatitude();//获取纬度
                    double longitude = amapLocation.getLongitude();//获取经度

                    MyConfig.Lat = latitude + "";
                    MyConfig.Lon = longitude + "";
                    String city = amapLocation.getCity();//城市信息
                    String district = amapLocation.getDistrict();//城区信息
                    String street = amapLocation.getStreet();//街道信息

                    LogUtils.d("lat :" + latitude + " ,lon :" + longitude + "city : "
                            + city + " : district :" + district + ", street :" + street);

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        fragmentManager =
                getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        chatFragment = new ChatFragment();
        transaction.replace(R.id.frame_home, chatFragment);
        transaction.commit();

        findViewById(R.id.ll_home).setOnClickListener(this);
        findViewById(R.id.ll_setting).setOnClickListener(this);
        findViewById(R.id.ll_message).setOnClickListener(this);
        findViewById(R.id.ll_find).setOnClickListener(this);

        txtTab1 = findViewById(R.id.txt_tab1);
        txtTab2 = findViewById(R.id.txt_tab2);
        txtTab3 = findViewById(R.id.txt_tab3);
        txtTab4 = findViewById(R.id.txt_tab4);

        ivTab1 = findViewById(R.id.iv_tab1);
        ivTab2 = findViewById(R.id.iv_tab2);
        ivTab3 = findViewById(R.id.iv_tab3);
        ivTab4 = findViewById(R.id.iv_tab4);

//        updateDialog("", "1.0.1");


        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        checkMyPermission(new PermissionListener(PermissionListener.Location) {
            @Override
            public void onPermissionClick() {
                if (null != mLocationClient) {
                    mLocationClient.setLocationOption(mLocationOption);
                    //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
                    mLocationClient.stopLocation();
                    mLocationClient.startLocation();
                }
            }
        });

        EventBus.getDefault().register(this);
        getAppConfig();
        getImToken();//获取融云的token
        onRequestInfo();
    }


    private void onRequestInfo() {
        HttpUtils.getInstance().toSubscribe(Api.getInstance().getUseInfo()
                , new SimpleSubscriber<HttpResult<UserModel>>() {
                    @Override
                    protected void _onNext(HttpResult<UserModel> o) {


                        if (o != null && o.getData() != null) {

                            final UserModel model = o.getData();

                            Hawk.put(MyConfig.SP_CACHE_USERMODEL, model);
                            UserInfoManager.uid = model.id;
                            UserInfoManager.is_rut = model.is_rut;
                            if (TextUtils.isEmpty(model.name)) {
                                goActivity(null, RegisterCompleteActivity.class);

                                return;
                            }
                            RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

                                @Override
                                public UserInfo getUserInfo(String userId) {

                                    UserInfo info = new UserInfo(model.id, model.name, Uri.parse(model.avatar_url));
                                    return info;
//                return findUserById(userId);//根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。
                                }
                            }, false);
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });


    }

    public void getImToken() {

        HttpUtils.getInstance().toSubscribe(Api.getInstance().getIMToken()
                , new SimpleSubscriber<HttpResult<QiNiuModel>>() {
                    @Override
                    protected void _onNext(HttpResult<QiNiuModel> o) {

                        QiNiuModel data = o.getData();
                        if (data != null) {

                            connect(data.token);
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    /**
     * <p>连接服务器，在整个应用程序全局，只需要调用一次，需在 {@link #(Context)} 之后调用。</p>
     * <p>如果调用此接口遇到连接失败，SDK 会自动启动重连机制进行最多10次重连，分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。
     * 在这之后如果仍没有连接成功，还会在当检测到设备网络状态变化时再次进行重连。</p>
     *
     * @param token 从服务端获取的用户身份令牌（Token）。
     * @return RongIM  客户端核心类的实例。
     */
    private void connect(String token) {

        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            /**
             * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
             *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
             */
            @Override
            public void onTokenIncorrect() {

            }

            /**
             * 连接融云成功
             * @param userid 当前 token 对应的用户 id
             */
            @Override
            public void onSuccess(String userid) {
                Log.d("LoginActivity", "--onSuccess" + userid);
            }

            /**
             * 连接融云失败
             * @param errorCode 错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventAppExit(EventAppExit model) {

        if (model.isExit) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void getAppConfig(){


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getAppConfig()
                , new SimpleSubscriber<HttpResult<AppConfigModel>>() {
                    @Override
                    protected void _onNext(HttpResult<AppConfigModel> o) {

                        final AppConfigModel data = o.getData();

                        Hawk.put(MyConfig.SP_CACHE_CONFIG,data);
                        boolean isDownload = DeviceHelper.verSionCompare(
                                DeviceHelper.installVersion(), data.version);
                        if (isDownload) {

                            new AlertDialog.Builder(HomeActivity.this).setMessage(data.desc).setTitle("V" + data.version + "版本更新")
                                    .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            if (!TextUtils.isEmpty(data.url) && data.url.contains("apk")) {

                                                updateDialog(data.url, data.version);
                                            } else {
                                                Intent intent = new Intent();
                                                intent.setAction("android.intent.action.VIEW");
                                                Uri content_url = Uri.parse(data.url);
                                                intent.setData(content_url);
                                                startActivity(intent);
                                            }
                                        }
                                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    dialog.dismiss();
                                }
                            }).show();
                        }

                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    ArrowDownloadButton updateBtnProgress;
    AlertDialog updateDialog;

    /**
     * 更新提示框
     */
    private void updateDialog(String url, String varName) {

        updateDialog = new AlertDialog.Builder(HomeActivity.this)
                .create();
        updateDialog.show();
        Window window = updateDialog.getWindow();
        window.setContentView(R.layout.layout_update);//设置弹出框加载的布局
        WindowManager.LayoutParams p = window.getAttributes();
        p.width = DensityUtils.dp2px(this, 200);
        p.gravity = Gravity.CENTER;
        window.setAttributes(p);
        updateBtnProgress = (ArrowDownloadButton) updateDialog.findViewById(R.id.btn_update);
        updateBtnProgress.startAnimating();
        DownloadApkThread thread = new DownloadApkThread(updateHandler, url, varName);
        thread.start();

    }

    private Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case DownloadApkThread.DOWNLOAD_PROGRESS:
                    if (updateBtnProgress != null) {

                        updateBtnProgress.setProgress(msg.arg1);
                    }

                    break;

                case DownloadApkThread.DOWNLOAD_FINISH:
                    String downloadPath = (String) msg.obj;
                    installApk(downloadPath);
                    if (updateBtnProgress != null) {

                        updateBtnProgress.reset();
                    }

                    if (updateDialog != null) {

                        updateDialog.dismiss();
                    }
                    break;
                case DownloadApkThread.DOWNLOAD_ERROR:

                    if (updateBtnProgress != null) {
                        updateBtnProgress.reset();
                    }

                    if (updateDialog != null) {
                        updateDialog.dismiss();
                    }
                    ToastUtils.show("下载出现错误...");
                    break;

                default:

                    break;
            }
        }
    };

    /**
     * 安装APK文件
     */
    private void installApk(String path) {
        File apkfile = new File(path);
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        startActivity(i);
    }


    @Override
    public void onClick(View view) {

        fragmentTransaction = fragmentManager.beginTransaction();
        initTab(fragmentTransaction);
        switch (view.getId()) {
            case R.id.ll_home:

                ivTab1.setImageResource(R.drawable.main_tab_item_icon1_selected);
                txtTab1.setTextColor(ContextCompat.getColor(this, R.color.color333));


                fragmentTransaction.show(chatFragment);

                break;

            case R.id.ll_setting:

                ivTab3.setImageResource(R.drawable.main_tab_item_icon4_selected);
                txtTab3.setTextColor(ContextCompat.getColor(this, R.color.color333));


                if (settingFragment == null) {
                    settingFragment = new MeSettingFragment();
                    fragmentTransaction.add(R.id.frame_home, settingFragment);
                } else {
                    fragmentTransaction.show(settingFragment);
                }

                break;
            case R.id.ll_message:
                ivTab2.setImageResource(R.drawable.main_tab_item_icon3_selected);
                txtTab2.setTextColor(ContextCompat.getColor(this, R.color.color333));

                if (imFragment == null) {
                    imFragment = new ChatIMFragment();
                    fragmentTransaction.add(R.id.frame_home, imFragment);
                } else {
                    fragmentTransaction.show(imFragment);
                }
                break;


            case R.id.ll_find:
                ivTab4.setImageResource(R.drawable.main_tab_item_icon2_selected);
                txtTab4.setTextColor(ContextCompat.getColor(this, R.color.color333));


                if (messageFragment == null) {
                    messageFragment = new MessageFragment();
                    fragmentTransaction.add(R.id.frame_home, messageFragment);
                } else {
                    fragmentTransaction.show(messageFragment);
                }

                break;


            default:

                break;

        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    private void initTab(FragmentTransaction fm) {

        ivTab1.setImageResource(R.drawable.main_tab_item_icon1);
        ivTab2.setImageResource(R.drawable.main_tab_item_icon3);
        ivTab3.setImageResource(R.drawable.main_tab_item_icon4);
        ivTab4.setImageResource(R.drawable.main_tab_item_icon2);

        txtTab1.setTextColor(ContextCompat.getColor(this, R.color.color999));
        txtTab2.setTextColor(ContextCompat.getColor(this, R.color.color999));
        txtTab3.setTextColor(ContextCompat.getColor(this, R.color.color999));
        txtTab4.setTextColor(ContextCompat.getColor(this, R.color.color999));


        if (chatFragment != null) {
            fm.hide(chatFragment);
        }
        if (settingFragment != null) {
            fm.hide(settingFragment);
        }
        if (imFragment != null) {
            fm.hide(imFragment);
        }
        if (messageFragment != null) {
            fm.hide(messageFragment);
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > TWO_SECOND) {
                ToastUtils.showToast(this, "再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);

                    ArrayList<ImageModel> list = new ArrayList<>();
                    if (localMedias != null && localMedias.size() > 0) {


                        for (int i = 0; i < localMedias.size(); i++) {

                            ImageModel model = new ImageModel();
                            model.imgPath = (localMedias.get(i).getCompressPath());
                            model.w = localMedias.get(i).getWidth();
                            model.h = localMedias.get(i).getHeight();
                            list.add(model);
                        }
                    }

                    Intent intent = new Intent(this, FindAddWeiboActivity.class);
                    intent.putExtra("list", list);
                    LogUtils.d("list :" + list.toString());
                    startActivity(intent);
                    break;
            }
        }
    }


    //发布任务
    public void onPublish(View view) {
        startActivity(new Intent(this, TaskPulishActivity.class));
    }
}
